package org.dromara.system.utils;


import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.mavenreposs.component.phpserialized.reader.PHPSerializedDataReader;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class PhpSerializeParser {

    public static String serialize(Map<String, Object> map) {
        StringBuilder sb = new StringBuilder();
        sb.append("a:").append(map.size()).append(":{");
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();

            // 处理键的序列化
            serializeString(key, sb);

            // 处理值的序列化
            if (value instanceof String) {
                serializeString((String) value, sb);
            } else if (value instanceof Integer) {
                sb.append("i:").append(value).append(";");
            } else if (value instanceof Double) {
                sb.append("d:").append(value).append(";");
            } else if (value instanceof Boolean) {
                sb.append("b:").append((Boolean) value ? "1" : "0").append(";");
            } else if (value == null) {
                sb.append("N;");
            } else {
                // 其他类型可能需要处理，例如嵌套数组或对象，此处省略
                throw new IllegalArgumentException("Unsupported type for PHP serialization");
            }
        }
        sb.append("}");
        return sb.toString();
    }

    private static void serializeString(String s, StringBuilder sb) {
        byte[] bytes = s.getBytes(StandardCharsets.UTF_8);
        sb.append("s:").append(bytes.length).append(":\"").append(s).append("\";");
    }

    public static Map<String, Object> parseMap(String serializedData) throws Exception {
        PHPSerializedDataReader reader = new PHPSerializedDataReader(serializedData);
        return reader.getFieldMap();
    }

    public static String parseStr(String serializedData) throws Exception {
        // 使用 Jackson 转换为 JSON 字符串
        ObjectMapper objectMapper = new ObjectMapper();
       return objectMapper.writeValueAsString(parseMap(serializedData));
    }

    public static String parse(String serializedData) {
        StringBuilder result = new StringBuilder();
        try {
            Map<String, Object> map = parseMap(serializedData);
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
                if(value instanceof HashMap) {
                    Map<String, Object> tempMap = (Map<String, Object>) value;
                    JSONArray jsonArray = new JSONArray();
                    tempMap.values().forEach((val) -> {
                        jsonArray.add(JSONObject.from(val));
                    });
                    value = jsonArray;
                }
                result.append(key).append(":").append(value).append(";");
            }
        } catch (Exception ignore){}
       return result.toString();
    }

    public static void main(String[] args) {
        String serializedData = "a:4:{s:4:\"size\";s:1:\"M\";s:13:\"Add your name\";s:1:\"1\";s:15:\"Add your number\";s:1:\"1\";s:8:\"_pao_ids\";a:2:{i:0;a:3:{s:3:\"key\";s:13:\"Add your name\";s:5:\"value\";s:1:\"1\";s:2:\"id\";i:1725110004;}i:1;a:3:{s:3:\"key\";s:15:\"Add your number\";s:5:\"value\";s:1:\"1\";s:2:\"id\";i:1725110005;}}}";

        try {
            System.out.println(parse(serializedData));
            // 输出解析后的数据
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
